package com.liuhung.base.util;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupUtil {

	/**
	 * 过滤html字符串中的样式部分并控制其中图片的大小 最大不能超过640px
	 * 
	 * @param html
	 * @return
	 */
	public static String clearStyle(String html, HttpServletRequest request) {
		Document doc = Jsoup.parse(html);
		Elements el = doc.getAllElements();
		for (Element e : el) {
			if (e.hasAttr("style")) {
				e.removeAttr("style");
			}
		}
		Elements imgs = doc.select("img");
		for (Element img : imgs) {
			String url = img.attr("src");
			if (!url.contains("http://")) {
				url = request.getScheme() + "://" + request.getServerName()
						+ ":" + request.getServerPort()
						+ request.getContextPath() + url;
			}
			int width = ImageUtil.getImgWidthWithUrl(url);
			if (width > 640) {
				img.attr("style", "width:640px");
			}
		}
		return doc.html();
	}
	public static String clearStyle(String html) {
		Document doc = Jsoup.parse(html);
		Elements el = doc.getAllElements();
		for (Element e : el) {
			if (e.hasAttr("style")) {
				e.removeAttr("style");
			}
		}
		return doc.html();
	}
	
	public static String readXml(URL url)
	{
		try {
			Document doc = Jsoup.parse(url, 2000);
			
			Elements ele = doc.select("rev");
			String content=ele.html();
			content=content.replaceAll("\\{{2}[^\\}]*?\\}{2}", ""); //去掉形如{{aa}}的内容
			content=content.replaceAll("'''", "");//去掉'''
			content=content.replaceAll("\\[{2}", "");//去掉[[]]
			content=content.replaceAll("\\]{2}", "");
			content=content.replaceAll("== 參見 ==.*", "");//去掉==参见==之后的内容.
			return content;
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}
}
